package org.algorithm.落雪.链表;

import org.algorithm.biubiu.wheel_1.common.ListNode;
import org.junit.Test;

/**
 * @author
 * @Date 2022/2/22
 * @Link {https://leetcode-cn.com/problems/SLwz0R/}
 */
public class 删除链表的倒数第n个结点 {

    @Test
    public void test() {
        ListNode listNode = removeNthFromEnd(ListNode.build(1, 2), 2);
        System.out.println("listNode = " + listNode);
    }

    //删除倒数第n个节点 = 删除正数第（L-n+1）个节点
    public org.algorithm.biubiu.wheel_1.common.ListNode removeNthFromEnd(ListNode head, int n) {

        //获取链表长度：L
        ListNode temp = new ListNode(0);
        temp.next = head;
        int length = 0;
        ListNode first = head;
        while (first != null) {
            length = length + 1;
            first = first.next;
        }

        //删除正数第（L-n+1）个节点
        length -= n;
        first = temp;
        while (length > 0) {
            length = length - 1;
            first = first.next;
        }
        first.next = first.next.next;

        return temp.next;
    }

}
